package com.bckj.fastboot.core.sql;

import java.util.List;

public class SqlUtils {

    public static Sql toCountSql(Sql sql) {
        Sql countSql;
        if (sql.getGroups().isEmpty()) {
             countSql = Sql.of(
                    List.of("COUNT(1)"),
                    sql.getFroms(),
                    sql.getJoins(),
                    sql.getLeftJoins(),
                    sql.getRightJoins(),
                    sql.getGroups(),
                    List.of(),
                    sql.getWheres()
            );
        } else {
            Sql innerSql = Sql.of(
                    List.of("*"),
                    sql.getFroms(),
                    sql.getJoins(),
                    sql.getLeftJoins(),
                    sql.getRightJoins(),
                    sql.getGroups(),
                    List.of(),
                    sql.getWheres()
            );
            countSql = Sql.of()
                    .select("COUNT(1)")
                    .from("(" + innerSql+ ") AS countSql");
        }
        return countSql;
    }
}
